package com.hlkj.warboot.configurer.util.excel.admin;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hlkj.warboot.configurer.util.ConvertUtils;
import com.hlkj.warboot.module_sys.entity.AdminEntity;
import com.hlkj.warboot.module_sys.service.AdminService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO 数据监听。DataListenerAdminEntity不能被spring管理，要每次读取excel都要new，然后里面用到spring可以构造方法传进去
 * @Author: lixing
 * @Date: 2020/12/5 9:30
 */
public class DataListenerAdminEntity extends AnalysisEventListener<ReadAdminEntity> {
    // 当readAdminEntityArrayList中的数据达到BATCH_COUNT了，则执行一次持久化并清空一次集合，防止内存溢出
    private static final int BATCH_COUNT = 100;
    private List<AdminEntity> readAdminEntityArrayList = new ArrayList<>();
    // 通过构造函数的方式把业务层接口注入
    private AdminService adminService;
    public DataListenerAdminEntity(AdminService adminService) {
        this.adminService = adminService;
    }

    /*
     * @Description TODO 持久化到数据库
     * @Author lixing
     * @Date 2020/12/5 9:57
     * @Param [] 
     * @return void
     */
    private void saveData() {
        // 持久化
        adminService.saveOrUpdateBatch(readAdminEntityArrayList);
        // 清除缓存
        readAdminEntityArrayList.clear();
    }

    /*
     * @Description TODO 读取表头数据
     * @Author lixing
     * @Date 2020/12/5 11:31
     * @Param [headMap, context] 
     * @return void
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        //System.out.println(JSONObject.toJSONString(headMap));
        //{0:"admin"}
        //{0:"创建时间",1:"账号",2:"年龄"}
    }

    /*
     * @Description TODO 每一条数据解析都会来调用
     * @Author lixing
     * @Date 2020/12/5 9:36
     * @Param [data, context] 
     * @return void
     */
    @Override
    public void invoke(ReadAdminEntity data, AnalysisContext context) {
        // 属性拷贝
        AdminEntity adminEntity = ConvertUtils.convert(data, AdminEntity.class);
        // 加入缓存
        readAdminEntityArrayList.add(adminEntity);
        // 批量处理
        if (readAdminEntityArrayList.size() >= BATCH_COUNT) {
            saveData();
        }
    }
    
    /*
     * @Description TODO 所有数据解析完成了都会来调用
     * @Author lixing
     * @Date 2020/12/5 9:37
     * @Param [context] 
     * @return void
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }
}
